<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="媒资名称" prop="mediaName">
            <el-input
                v-model="queryParams.mediaName"
                placeholder="请输入媒资名称"
                clearable
                style="width: 240px"
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="媒资类型" prop="mediaTypeList">
            <el-select
                v-model="queryParams.mediaType"
                placeholder="媒资类型"
                clearable
                style="width: 240px"
            >
              <el-option
                  v-for="item in mediaTypeList"
                  :key="item.id"
                  :label="item.typeName"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleAdd"
                v-hasPermi="['media:mediaSource:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="danger"
                plain
                icon="Delete"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['media:mediaSource:remove']"
            >删除
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" border :data="mediaSourceList" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" :resizable="true" align="center"/>
          <el-table-column label="媒资名称" :resizable="true" align="center" key="mediaName" prop="mediaName" v-if="columns[0].visible"/>
          <el-table-column label="播放时长" :resizable="true" align="center" key="timeLength" prop="timeLength" v-if="columns[1].visible"
                           :show-overflow-tooltip="true"/>
          <el-table-column label="文件大小" :resizable="true" align="center" key="fileSize" prop="fileSize" v-if="columns[2].visible"
                           :show-overflow-tooltip="true"/>
          <el-table-column label="媒资类型" :resizable="true" align="center" key="mediaTypeName" prop="mediaTypeName"
                           v-if="columns[3].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="访问级别" :resizable="true" align="center" key="accessLevel" prop="accessLevel"
                           v-if="columns[4].visible">
            <template #default="scope">
              <dict-tag :options="t_media_access_level" :value="scope.row.accessLevel"/>
            </template>
          </el-table-column>
          <el-table-column label="审核状态" :resizable="true" align="center" prop="reviewStatus" v-if="columns[5].visible">
            <template #default="scope">
              <dict-tag :options="t_review_status" :value="scope.row.reviewStatus"/>
            </template>
          </el-table-column>
          <el-table-column label="上传时间" :resizable="true" align="center" prop="uploadTime" v-if="columns[6].visible">
            <template #default="scope">
              <span>{{ parseTime(scope.row.uploadTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="文件试听" :resizable="false" width="300px;" align="center" prop="uploadTime" v-if="columns[6].visible">
            <template #default="scope">
              <VideoFlv :src="scope.row.fileName" :mediaType="'mp3'" controls="controls" style="width: 300px; height: 30px;"></VideoFlv>
            </template>
          </el-table-column>
          <el-table-column label="操作" :resizable="true" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-tooltip content="修改" placement="top" v-if="scope.row.userId !== 1">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                           v-hasPermi="['media:mediaSource:edit']"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top" v-if="scope.row.userId !== 1">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                           v-hasPermi="['media:mediaSource:remove']"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body  @close="cancel">
      <el-form :model="addform" :rules="addFormRules" ref="addMediaRef" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="媒资名称" prop="mediaName">
              <el-input v-model="addform.mediaName" placeholder="请输入媒资文件名称" maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>
        <div v-if="!addform.id">
          <el-row>
            <el-col :span="24">
              <el-form-item label="上传模式">
                <el-radio-group v-model="uploadType" @change="uploadTypeChange()">
                  <el-radio
                      v-for="dict in uploadTypeOptions"
                      :key="dict.value"
                      :label="dict.value"
                  >{{ dict.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="uploadType==0" v-hasPermi="['media:mediaSource:uploadFile']">
            <el-col :span="12" >
              <el-form-item label="上传" >
                <el-upload
                    ref="uploadRef"
                    :limit="1"
                    accept=".mp3,.mp4,.txt,.jpg,.png"
                    :headers="upload.headers"
                    :action="upload.url"
                    :disabled="upload.isUploading"
                    :on-progress="handleFileUploadProgress"
                    :on-success="handleFileSuccess"
                    :auto-upload="false"
                    drag
                >
                  <el-icon class="el-icon--upload">
                    <upload-filled/>
                  </el-icon>
                  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <div class="el-upload__text">文件格式限制 mp3/mp4/txt/jpg/png</div>
              <el-button type="primary" @click="uploadFile">确 定 上 传</el-button>
            </el-col>
          </el-row>
          <el-row v-if="uploadType==1" v-hasPermi="['media:mediaSource:uploadFile']">
            <el-col :span="16" >
              <el-form-item label="文字内容" >
                <el-input v-model="addform.detail" type="textarea" placeholder="请输入内容"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="" >
                <div class="el-upload__text">文字内容需要文转语</div>
                <el-button type="primary" @click="toTTS">确 定 文 转 语</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="文件名称" prop="fileName">
              <el-input v-model="addform.fileName" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文件大小" prop="fileSize">
              <el-input v-model="addform.fileSize" readonly/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="文件类型" prop="fileType">
              <el-select
                  v-model="addform.fileType"
                  placeholder="文件类型"
                  clearable
                  style="width: 100%"
                  :disabled="true"
              >
                <el-option
                    v-for="item in t_media_file_type"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文件时长" prop="timeLength">
              <el-input v-model="addform.timeLength" readonly/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="媒资分类" prop="mediaType">
              <el-select
                  v-model="addform.mediaType"
                  placeholder="媒资分类"
                  clearable
                  style="width: 100%"
              >
                <el-option
                    v-for="item in mediaTypeList"
                    :key="item.id"
                    :label="item.typeName"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="访问级别" prop="accessLevel">
              <el-select
                  v-model="addform.accessLevel"
                  placeholder="访问级别"
                  clearable
                  style="width: 100%"
              >
                <el-option
                    v-for="item in t_media_access_level"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MediaSource">
import {getToken} from "@/utils/auth";
import {
  listMediaSource,
  deleteFile,
  addMediaSource,
  updateMediaSource,
  delMediaSource,
  tts
} from "@/api/system/mediaSource";
import {
  getMediaTypeAll
} from "@/api/system/mediaType";

const {proxy} = getCurrentInstance();
const {
  t_media_access_level,
  t_review_status,
  t_media_file_type
} = proxy.useDict("t_media_access_level", "t_review_status", "t_media_file_type");

const mediaSourceList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const mediaTypeList = ref([]);
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: {Authorization: "Bearer " + getToken()},
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/media/mediaSource/uploadFile"
});

// 列显隐信息
const columns = ref([
  {key: 0, label: `媒资名称`, visible: true},
  {key: 1, label: `播放时长`, visible: true},
  {key: 2, label: `文件大小`, visible: true},
  {key: 3, label: `媒资类型`, visible: true},
  {key: 4, label: `访问级别`, visible: true},
  {key: 5, label: `审核状态`, visible: true},
  {key: 6, label: `上传时间`, visible: true}
]);

const data = reactive({
  addform: {
    id: undefined,
    fileName: undefined,
    mediaName: undefined,
    timeLength: undefined,
    fileSize: undefined,
    fileType: undefined,
    accessLevel: undefined,
    mediaType: undefined,
    filePath:undefined,
    detail:undefined
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    mediaName: undefined,
    mediaType: undefined
  },
  addFormRules: {
    mediaName: [{ required: true, message: "媒资名称不能为空", trigger: "blur" }],
    fileName: [{ required: true, message: "请先上传文件", trigger: "blur" }],
    mediaType: [{ required: true, message: "请选择媒资类型", trigger: "blur" }],
    accessLevel: [{ required: true, message: "请选择访问级别", trigger: "blur" }]
  },
  uploadType: 0,
  uploadTypeOptions:[{
    value:1,
    label:"文字输入"
  },{
    value:0,
    label:"文件上传"
  }]
});

const {queryParams, addform,addFormRules,uploadType,uploadTypeOptions} = toRefs(data);


/** 查询用户列表 */
function getList() {
  loading.value = true;
  listMediaSource(queryParams.value).then(res => {
    loading.value = false;
    mediaSourceList.value = res.rows;
    total.value = res.total;
  });
  getMediaTypeAll().then(res => {
    mediaTypeList.value = res.data;
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.regionId = undefined;
  handleQuery();
}

/** 删除按钮操作 */
function handleDelete(row) {
  const Ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除编号为"' + Ids + '"的数据项？').then(function () {
    return delMediaSource(Ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}


/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}


/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "上传结果", {dangerouslyUseHTMLString: true});
  if(response.code != 200){
    return;
  }
  addform.value.fileSize = response.data.fileSize;
  addform.value.timeLength = response.data.timeLength;
  addform.value.fileType = response.data.fileType;
  addform.value.fileName = response.data.fileName;
  addform.value.filePath = response.data.filePath;
  addform.value.detail = response.data.detail;
}

function uploadFile(){
  proxy.$refs["uploadRef"].submit();
}


/** 重置操作表单 */
function reset() {
  addform.value = {
    id: undefined,
    fileName: undefined,
    mediaName: undefined,
    timeLength: undefined,
    fileSize: undefined,
    fileType: undefined,
    accessLevel: undefined,
    mediaType: undefined,
    filePath:undefined
  };
  proxy.resetForm("addMediaRef");
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  if(addform.value.filePath !== undefined && addform.value.id === undefined){
    deleteFile(addform.value).then(()=>{});
  }
  reset();
}

/** 新增按钮操作 */
function handleAdd() {
  open.value = true;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  open.value = true;
  addform.value.fileSize = row.fileSize;
  addform.value.id = row.id;
  addform.value.timeLength = row.timeLength;
  addform.value.fileType = row.fileType;
  addform.value.fileName = row.fileName;
  addform.value.filePath = row.filePath;
  addform.value.mediaName = row.mediaName;
  addform.value.accessLevel = row.accessLevel;
  addform.value.mediaType = row.mediaType;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["addMediaRef"].validate(valid => {
    if (valid) {
      if (addform.value.id !== undefined) {
        updateMediaSource(addform.value).then(response => {
          if(response.code == 200){
            proxy.$modal.msgSuccess(response.msg);
          }else{
            proxy.$modal.msgError(response.msg);
          }
          open.value = false;
          reset();
          getList();
        });
      } else {
        addMediaSource(addform.value).then(response => {
          if(response.code == 200){
            proxy.$modal.msgSuccess(response.msg);
          }else{
            proxy.$modal.msgError(response.msg);
          }
          open.value = false;
          reset();
          getList();
        });
      }
    }
  });
}

function uploadTypeChange(){
  if(uploadType.value=== 0){
    addform.value.detail = undefined;
  }
}

function toTTS(){
  tts(addform.value).then(response => {
    if(response.code != 200){
      proxy.$modal.msgError(response.msg);
      return;
    }
    proxy.$modal.msgSuccess(response.msg);
    addform.value.fileSize = response.data.fileSize;
    addform.value.timeLength = response.data.timeLength;
    addform.value.fileType = response.data.fileType;
    addform.value.fileName = response.data.fileName;
    addform.value.filePath = response.data.filePath;
  });
}

getList()
</script>
